# 使用Python 3.11 slim作为基础镜像
FROM python:3.11-slim

# 设置环境变量
ENV PYTHONUNBUFFERED=1
ENV PYTHONDONTWRITEBYTECODE=1
ENV PIP_NO_CACHE_DIR=1
ENV PIP_DISABLE_PIP_VERSION_CHECK=1

# 设置工作目录
WORKDIR /app

# 安装系统依赖
RUN apt-get update && apt-get install -y \
    gcc \
    g++ \
    curl \
    wget \
    git \
    build-essential \
    libpq-dev \
    libffi-dev \
    libssl-dev \
    libxml2-dev \
    libxslt1-dev \
    libjpeg-dev \
    libfreetype6-dev \
    zlib1g-dev \
    nginx \
    supervisor \
    && rm -rf /var/lib/apt/lists/*

# 安装Python依赖
COPY requirements.txt .
RUN pip install --upgrade pip && \
    pip install -r requirements.txt

# 创建非root用户
RUN groupadd -r maess && useradd -r -g maess maess

# 创建必要的目录
RUN mkdir -p /app/logs /app/data /app/temp /app/search_index && \
    chown -R maess:maess /app

# 复制应用代码
COPY --chown=maess:maess . /app

# 复制配置文件
COPY deploy/supervisord.conf /etc/supervisor/conf.d/supervisord.conf
COPY deploy/nginx.conf /etc/nginx/nginx.conf

# 设置权限
RUN chmod +x /app/deploy/*.sh && \
    chown -R maess:maess /app

# 切换到非root用户
USER maess

# 暴露端口
EXPOSE 8000 8001 5555

# 健康检查
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
    CMD curl -f http://localhost:8000/health || exit 1

# 启动命令
CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/conf.d/supervisord.conf"]